#pragma once
#include "exports.h"

template<typename T>
uint8_t EncodeVarInt(char *dst, T v) 
{
  static const uint8_t B = 128;
  char *ptr = dst;
  while (v >= B) {
    *(ptr++) = v | B;
    v >>= 7;
  }
  *(ptr++) = v;
  return ptr - dst;
}

template<typename T>
T DecodeVarInt(const char *&source) 
{
  static const uint8_t B = 128;
  T res = 0;
  uint8_t length = 1;
  while (B & *(source++)) {
    ++length;
  }
  char *src_ptr = (char *)source - 1;
  do {
    res <<= 7;
    res |= (B-1) & static_cast<T>(*(src_ptr--));
  } while (--length);
  return res;
}

template<typename T>
void PutVarInt(std::string &dst, T v)
{
  char buf[10];
  dst.append(buf, EncodeVarInt(buf, v));
}

void PutLengthPrefixedSView(std::string &dst, const SView& value) {
  PutVarInt(dst, value.size());
  dst.append(value.data(), value.size());
}